package cn.akwangl.socket.aio.simple;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理客户端连接,维护socketChannel 通道.
 *
 * @author 阿坤同学
 * @date 2022/6/26 15:37
 * @since 0.0.6
 */
@Slf4j
public class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {

    @Override
    public void completed(AsynchronousSocketChannel asynchronousSocketChannel, AsynchronousServerSocketChannel asynchronousServerSocketChannel) {
        // 创建client channel 监听
        if (asynchronousServerSocketChannel.isOpen()) {
            asynchronousServerSocketChannel.accept(null, this);
        }

        try {
            // 处理client 读写
            if (asynchronousSocketChannel != null && asynchronousSocketChannel.isOpen()) {
                log.info("客户端:{},建立连接", asynchronousSocketChannel.getRemoteAddress());
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                Map<String, Object> map = new HashMap<>();
                map.put("type", "read");
                map.put("data", byteBuffer);
                asynchronousSocketChannel.read(byteBuffer, map, new ClientHandler(asynchronousSocketChannel));
            }
        } catch (IOException e) {
            log.error("监听client socket channel 失败", e);
        }
    }

    @Override
    public void failed(Throwable exc, AsynchronousServerSocketChannel asynchronousServerSocketChannel) {
        log.error("监听 client socket channel 失败", exc);
    }
}
